package com.watson.todolist;

import java.io.IOException;
import java.security.GeneralSecurityException;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;

import com.watson.todolist.constants.DatabaseConstants;
import com.watson.todolist.database.AccountManager;
import com.watson.todolist.database.DatabaseManager;
import com.watson.todolist.database.GenericEncryption;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Toast;

/**
 * This is the forgetPassword activity page which displays the security options
 * for the user to retrieve or recreate his password.
 * 
 * @author Jasmin Muminhodzic
 * @version 1.0
 * 
 */
public class forgotPasswordPage extends Activity {

	AccountManager accountManager;
	Button submit;
	Button cancel;
	EditText userInfo; // can be username or email address

	/**
	 * This method is called when the activity is created.
	 * 
	 * @param savedInstanceState
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.forgotpasswordlayout);

		accountManager = AccountManager.getAccountManager();

		submit = (Button) findViewById(R.id.ForgotPassSubmit);
		submit.setOnClickListener(forgotPassListener);
		cancel = (Button) findViewById(R.id.ForgotPassCancel);
		cancel.setOnClickListener(forgotPassListener);

		userInfo = (EditText) findViewById(R.id.userInfo);

	}

	/**
	 * This functions as the listener object for both buttons on the forgot
	 * password page. The submit button checks if a given user exists and if so
	 * emails their password. The cancel button returns the view to the main
	 * login screen.
	 */
	private OnClickListener forgotPassListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			// if submit button pressed
			if (v == submit) {

				// set up inflater for custom "toast" message
				LayoutInflater inflater = getLayoutInflater();
				View toastLayout = inflater.inflate(R.layout.custom_toast,
						(ViewGroup) findViewById(R.id.custom_toast_root));

				String userInfoString = userInfo.getText().toString();

				// Send user change password code via email
				DatabaseManager dbManager = new DatabaseManager();
				SQLiteDatabase db = dbManager.open(getApplicationContext());
				AccountManager manager = new AccountManager(db);

				// if a username or email address exists with the given string
				if (accountManager.userNameExistence(userInfoString)
						|| accountManager.userEmailExistence(userInfoString)) {

					String userEmail;

					// if the string matches a username
					if (accountManager.userNameExistence(userInfoString)) {

						// Get users email
						Cursor c = manager
								.getUserAccountByUserName(userInfoString);
						userEmail = c
								.getString(c
										.getColumnIndex(DatabaseConstants.ACCOUNT_TABLE_EMAIL_ADDRESS));
					}

					// if the string matches an email address
					// note: validity of email format already checked upon
					// creation
					else {
						Cursor c = manager
								.getUserAccountByUserEmail(userInfoString);
						userEmail = c
								.getString(c
										.getColumnIndex(DatabaseConstants.ACCOUNT_TABLE_EMAIL_ADDRESS));
					}

					try {
						manager.sendUserPasswordCodeViaEmail(
								getApplicationContext(), userEmail,
								userInfoString);

						// Get change password code to send to next screen
						String changePasswordCode = GenericEncryption
								.encrypt(userInfoString);

						// setting image of custom toast message
						((ImageView) toastLayout.findViewById(R.id.toastImg))
								.setImageResource(R.drawable.check_img);
						// setting text of custom toast message
						((TextView) toastLayout.findViewById(R.id.toastText))
								.setText("Your unique change password code will be sent to you via email.");
						// display message
						Toast passwordSent = Toast.makeText(
								getApplicationContext(), "", 4000);
						passwordSent.setView(toastLayout);
						passwordSent.show();

						Intent myIntent = new Intent(v.getContext(),
								ResetPassword.class);
						myIntent.putExtra("code", changePasswordCode);
						myIntent.putExtra("username", userInfoString);
						startActivity(myIntent);

					} catch (Exception e) {
						// setting image of custom toast message
						((ImageView) toastLayout.findViewById(R.id.toastImg))
								.setImageResource(R.drawable.check_img);
						// setting text of custom toast message
						((TextView) toastLayout.findViewById(R.id.toastText))
								.setText("ERROR: Failed to send password code.");
						Toast passwordSent = Toast.makeText(
								getApplicationContext(), "", 4000);
						passwordSent.setView(toastLayout);
						passwordSent.show();
						e.printStackTrace();
					}
				}

				// string does not match username or email address
				else {

					// setting image of custom toast message
					((ImageView) toastLayout.findViewById(R.id.toastImg))
							.setImageResource(R.drawable.error_img);
					// setting text of custom toast message
					((TextView) toastLayout.findViewById(R.id.toastText))
							.setText("ERROR: Username or email address does not exist");

					Toast userError = Toast.makeText(getApplicationContext(),
							"Username does not exist", 4000);
					userError.setView(toastLayout);
					userError.show();
				}
			}

			// if cancel button pressed
			// go back to main login page
			else {

				Intent myIntent = new Intent(v.getContext(),
						mainLoginPage.class);
				startActivity(myIntent);
			}
		}
	};

}